// pages/mine_info/mine_info.js
const app = getApp(), core = require('../../utils/core'), WeValidator = require('../../utils/we-validator');
Page({

  /**
   * 页面的初始数据
   */
  data: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let page = this;
    core.get({url:'/xilujob.user/profile', loading:false, success(ret,response){
      page.setData({user: ret.data.profile});
    }});
  },
  upload: function() {
    let page = this;
    wx.chooseImage({
      success: res => {
        let file = res.tempFiles[0];
        core.uploadFile({
          filePath: file.path,
          success(ret, response) {
            page.setData({'user.avatar': ret.data.url});
          }
        });
      }
    });
  },
  save(event) {
    let data = event.detail.value;
    let validator = new WeValidator({
      rules: {
        avatar: {required:true},
        nickname: {required:true,maxlength:50}
      },
      messages: {
        avatar: {required:'请上传头像'},
        nickname:{required:'请填写昵称',maxlength:'昵称最多50个字符'}
      }
    });
    if(!validator.checkData(data)) {
      return;
    }
    core.post({
      url: 'xilujob.user/profile',
      data: data,
      success(ret, response) {
        let profile = ret.data.profile;
        let userinfo = app.getUserinfo();
        userinfo.avatar = data.avatar;
        userinfo.nickname = data.nickname;
        app.setUserinfo(userinfo);
        app.eventBus.emit(app.Events.UserProfileUpdate, profile);
        wx.navigateBack();
        wx.showToast({
          title: '修改成功',
          icon: 'none'
        })
      }
    })
  }

});
